{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Higher dimensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finite difference generalizes readily to multiple dimensions, by computing the elements of the gradient individually:\n", "\n", "$$\n", "\\frac{\\partial f}{\\partial x_i} ≈ \\frac{f(x + heᵢ) - f(x - heᵢ)} {2h} $$\n", "\n", "Boundary cases are handelled similarly but with the bounded dimension calculated by forward / backward difference.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "
\n", "
\n", "\n", "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# prompt: Give me an example of an ugly 2D function, plot it as a surface in plotly and show its gradients in arrows\n", "\n", "import numpy as np\n", "import plotly.graph_objects as go\n", "import plotly.figure_factory as ff\n", "\n", "# Define the function\n", "def ugly_function(x, y):\n", " return (np.sin(x) * np.cos(y) + np.cos(x) * np.sin(y)) * np.exp(-(x**2 + y**2) / 10)\n", "\n", "# Create a grid of x and y values\n", "x = np.linspace(-5, 5, 50)\n", "y = np.linspace(-5, 5, 50)\n", "X, Y = np.meshgrid(x, y)\n", "\n", "# Calculate the function values and gradients\n", "Z = ugly_function(X, Y)\n", "dZdx, dZdy = np.gradient(Z)\n", "\n", "# Create the surface plot\n", "fig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y)])\n", "fig.update_layout(title='Ugly 2D Function', autosize=False,\n", " width=500, height=500,\n", " margin=dict(l=65, r=50, b=65, t=90))\n", "\n", "# Add gradient arrows to the plot\n", "arrow_x = X[::5, ::5].flatten()\n", "arrow_y = Y[::5, ::5].flatten()\n", "arrow_z = Z[::5, ::5].flatten()\n", "arrow_u = dZdx[::5, ::5].flatten()\n", "arrow_v = dZdy[::5, ::5].flatten()\n", "\n", "\n", "fig.add_trace(go.Cone(\n", " x=arrow_x,\n", " y=arrow_y,\n", " z=arrow_z,\n", " u=arrow_u,\n", " v=arrow_v,\n", " w=np.zeros_like(arrow_u),\n", " sizemode=\"absolute\",\n", " sizeref=0.1,\n", " showscale=False,\n", " colorscale='Blues'\n", "))\n", "\n", "fig.show()\n" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }